﻿#region Copyright Notice
// 
// 
// Copyright (c) 2009-2010 Anindya Chatterjee
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// 
// 
#endregion
using System;
using System.IO;
using System.Net;
using System.Serialization.Xml;
using System.Windows.Forms;
using Event.Plugin;
using Event.Plugin.Configuration;
using GmailNotifier.Atom;

namespace GmailNotifier
{
    public class Gmail : AbstractEvent
    {
        private readonly Uri _gmailFeedUri = new Uri(@"https://mail.google.com/mail/feed/atom/");
        private int _errorCounter;
        private Feed _gmailFeed;
        private int _initialCount;
        

        public override void InitializeEvent()
        {
            base.InitializeEvent();
            ListeningInterval = 100;
            EventSettings = new GmailSettings().Load();
            Loop = true;
            
        }

        public override void Notify()
        {
            if (_gmailFeed != null)
            {
                var notify = new GmailNotify(this);
                notify.LoadEmails(_gmailFeed);

                UserNotifier.StartAnimateIcon();
                UserNotifier.ShowNotifyTipNow(notify);
                UserNotifier.PlaySound();
            }
        }

        public override void EventLogic()
        {
            try
            {
                if (!string.IsNullOrEmpty(((GmailSettings) EventSettings).GmailId)
                    && !string.IsNullOrEmpty(((GmailSettings) EventSettings).Password))
                {
                    WebRequest request = WebRequest.CreateDefault(_gmailFeedUri);
                    request.Credentials = new NetworkCredential(((GmailSettings) EventSettings).GmailId,
                                                                ((GmailSettings) EventSettings).Password);

                    if (((AppConfig) ApplicationSettings).UseProxy)
                    {
                        WebProxy proxy = ((AppConfig) ApplicationSettings).Proxy;
                        request.Proxy = proxy;
                    }
                    var response = request.GetResponse() as HttpWebResponse;
                    if (response != null)
                    {
                        // reset error counter.
                        _errorCounter = 0;
                        lock (this)
                        {
                            Stream xmlStream = response.GetResponseStream();
                            TextReader reader = new StreamReader(xmlStream);
                            string xml = reader.ReadToEnd();
                            var serializer = new XObjectSerializer<Feed>();
                            _gmailFeed = serializer.Deserialize(xml);
                            if (_gmailFeed.Fullcount > _initialCount)
                            {
                                ListeningComplete = true;
                            }
                            _initialCount = _gmailFeed.Fullcount;
                            xmlStream.Close();
                        }
                    }
                }
            }
            catch (WebException)
            {
                _errorCounter++;
                if (_errorCounter >= 3)
                {
                    EndListening();
                    MessageBox.Show("\nGmail notifier is inactivated. To activate it again restart Ozone.", "Gmail Connection Failure");
                }
                else if(_errorCounter >= 1)
                {
                    MessageBox.Show("\nPlease check your internet connection.", "Gmail Connection Failure");
                    // sleep for 30 min for connection repair.
                    Sleep(30*60*1000);
                }
            }
        }
    }
}